package com.octopus.kernal.util.generate;

import java.io.FileReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.octopus.kernal.util.xml.*;

public class CodeGenerator {
	
	private static Log log = LogFactory.getLog(CodeGenerator.class);
	
	public static void main(String[] args) throws Exception {
		String basePackage = args[0];
		String fileBusinessModel = args[1] + "/src/main/resources/BusinessModel.xml";
		Exception exception = null;
		JAXBContext context = JAXBContext.newInstance(BusinessModel.class);
		Unmarshaller unmarshal = context.createUnmarshaller();
		FileReader reader = new FileReader(fileBusinessModel);
		BusinessModel model = (BusinessModel)unmarshal.unmarshal(reader);
		JavaCodeGenerator javaGenerator = new JavaCodeGenerator(basePackage, model);
		JspCodeGenerator jspGenerator = new JspCodeGenerator(args[1], model);
		PropertiesGenerator propertiesGenerator = new PropertiesGenerator(args[1], model);
		if(model != null && model.getEntities() != null){
			for(Entity entity : model.getEntities()){
				try {
					// Java generate
					javaGenerator.generatePersistModel(entity);
					javaGenerator.generatePersistDao(entity);
					javaGenerator.generateService(entity);
					javaGenerator.generateValidator(entity);
					javaGenerator.generateSearchCommand(entity);
					javaGenerator.generateController(entity);
					
					// JSP generate
					jspGenerator.generateQueryPage(entity);
					jspGenerator.generateEditPage(entity);
				} catch (ClassNotFoundException e) {
					exception = e;
					continue;
				} catch (Exception e){
					exception = e;
					continue;
				}

			}
			try{
				// Properties generate
				propertiesGenerator.generateI18nSampleProperties(model);
			}catch (Exception e){
				exception = e;
			}
		}
		if(exception != null){
			reader.close();
			throw exception;
		}
		reader.close();
		
		log.info("Class generation finished for the package: " + basePackage);
	}

}
